package com.ytc.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ytc.commons.constants.CourseConstants;
import com.ytc.commons.enums.ErrorCode;
import com.ytc.commons.model.dto.BindTeachplanMediaDto;
import com.ytc.commons.model.dto.TeachplanDto;
import com.ytc.commons.model.vo.MediaVo;
import com.ytc.commons.model.vo.ResponseResult;
import com.ytc.commons.model.vo.TeachplanVo;
import com.ytc.commons.utils.BeanHelper;
import com.ytc.content.domain.CourseBase;
import com.ytc.content.domain.Teachplan;
import com.ytc.content.domain.TeachplanMedia;
import com.ytc.content.mappers.TeachplanMapper;
import com.ytc.content.service.CourseBaseService;
import com.ytc.content.service.TeachplanMediaService;
import com.ytc.content.service.TeachplanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ytc.media.api.MediaClient;
import com.ytc.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程计划 服务实现类
 * </p>
 *
 * @since 2023-04-01
 */
@Service
public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService {


    //根据课程id查询课程的章节
    @Override
    public ResponseResult<TeachplanVo> treeNodes(Long courseId) {
         //调用mapper根据id查询,查出一二三级
        List<TeachplanVo> teachplanVoList=this.baseMapper.treeNodes(courseId);
        //筛选一级大纲
        TeachplanVo parent = teachplanVoList.stream()
                .filter(vo -> vo.getGrade()==1)
                .findFirst()
                .get();
        //筛选二级大纲，将二级大纲set到一级大纲
        List<TeachplanVo> list = teachplanVoList.stream()
                .filter(vo -> vo.getGrade()==2)
                .collect(Collectors.toList());
        parent.setTeachPlanTreeNodes(list);
        //筛选三级大纲
        for (TeachplanVo teachplanVo : list) {
            List<TeachplanVo> three =teachplanVoList.stream()
                    .filter(vo->vo.getGrade()==3 && vo.getParentid().equals(teachplanVo.getId()))
                    .collect(Collectors.toList());
            teachplanVo.setTeachPlanTreeNodes(three);
        }
        return ResponseResult.okResult(parent);
    }


    //保存或者更新课程章节
    @Autowired
    private CourseBaseService courseBaseService;
    @Override
    public void saveOrUpdateTeachplan(TeachplanDto dto) {
       Long courseId = dto.getCourseId();
        //2.处理前端传过来的Parentid为空的情况(保存二级大纲) ，查询1级大纲的id（也就是parentid）
        if(dto.getParentid() == null){
            LambdaQueryWrapper<Teachplan> qw = new LambdaQueryWrapper();
            qw.eq(Teachplan::getGrade,1);
            qw.eq(Teachplan::getCourseId,courseId);
            Teachplan teachplan = this.getOne(qw);  //得到parentid
            dto.setParentid(teachplan.getParentid());
        }
        //3.判断是更新还是添加章节
        Teachplan teachplan = BeanHelper.copyProperties(dto, Teachplan.class);
        //3.1如果id不存在就保存  并且判断新增的是几级章节如果是三级请让，course_base表里总小结数加一
        if(teachplan.getId() == null && teachplan.getGrade()==3){
            this.save(teachplan);
            //执行课程表里面的章节数+1操作
            CourseBase courseBase = courseBaseService.getById(teachplan.getCourseId());
            LambdaUpdateWrapper<CourseBase> qw = new LambdaUpdateWrapper<>();
            qw.eq(CourseBase::getId,teachplan.getCourseId());
            qw.set(CourseBase::getPlanNum,courseBase.getPlanNum()+1);
            courseBaseService.update(qw); //修改章节数目

        }else if(teachplan.getId() == null && teachplan.getGrade()==2){
            //保存的是二级章节，小章节不需要加一
            this.save(teachplan);
        }else//3.2id存在就更新
            this.updateById(teachplan);
    }

    //删除章节
    @Override
    public ResponseResult deleteTeachplan(Long id) {
        //1.判断要删除的章节是不是三级章节，如果是总章节数减一，若不是就直接删除
        Teachplan teachplan = this.getById(id);
        if(teachplan.getGrade()==3){
            this.removeById(id);
            //执行课程表里面的章节数-1操作
            CourseBase courseBase = courseBaseService.getById(teachplan.getCourseId());
            LambdaUpdateWrapper<CourseBase> qw = new LambdaUpdateWrapper<>();
            qw.eq(CourseBase::getId,teachplan.getCourseId());
            qw.set(CourseBase::getPlanNum,courseBase.getPlanNum()-1);

            courseBaseService.update(qw); //修改章节数目
        }else
            this.removeById(id);

        return ResponseResult.okResult();
    }


    @Autowired
    private MediaClient mediaClient;
    @Autowired
    private TeachplanMediaService teachplanMediaService;
    //课程计划绑定视频
    @Override
    public ResponseResult associationMedia(BindTeachplanMediaDto dto) {
        //1、查询当前课程计划所属的课程，根据课程计划id，查询课程计划
        Teachplan teachplan = this.getById(dto.getTeachplanId());
        Long courseId = teachplan.getCourseId();
        //判断课程状态
        CourseBase courseBase = courseBaseService.getById(courseId);
        String auditStatus = courseBase.getAuditStatus();
        if (CourseConstants.AUDIT_PUBLISHED_STATUS.equals(auditStatus) ||
                CourseConstants.AUDIT_PASTED_STATUS.equals(auditStatus) ||
                CourseConstants.AUDIT_COMMIT_STATUS.equals(auditStatus)) {
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        //2、调用feign接口查询媒资
        ResponseResult<MediaVo> result = mediaClient.findById(dto.getMediaId());
        MediaVo mediaVo = result.getData();
        //3、查询当前课程计划所绑定的媒资数据
        LambdaQueryWrapper<TeachplanMedia> qw = new LambdaQueryWrapper<>();
        qw.eq(TeachplanMedia::getTeachplanId,dto.getTeachplanId());
        TeachplanMedia teachplanMedia = teachplanMediaService.getOne(qw);
        //3.1 如果不存在，保存
        if(teachplanMedia == null) {
            teachplanMedia = new TeachplanMedia();
            teachplanMedia.setMediaId(dto.getMediaId());
            teachplanMedia.setMediaFilename(mediaVo.getFilename());
            teachplanMedia.setCourseId(courseId);
            teachplanMedia.setTeachplanId(dto.getTeachplanId());
            teachplanMedia.setCreateDate(new Date());
            teachplanMediaService.save(teachplanMedia);
        }else {
            //3.2 如果存在，更新
            teachplanMedia.setMediaId(dto.getMediaId());
            teachplanMedia.setMediaFilename(mediaVo.getFilename());
             teachplanMediaService.updateById(teachplanMedia);
        }

        return ResponseResult.okResult();
    }


    //解除视频与课程计划的绑定
    @Override
    public ResponseResult teachPlanMediaId(Long teachPlanMediaId, Long courseBaseId) {


        teachplanMediaService.removeById(teachPlanMediaId);
        return ResponseResult.okResult();
    }
}
